﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Exortech.NetReflector;

namespace ccnet.assemblypatcher.plugin
{
    [ReflectorType("assemblypatcher")]
    public class AssemblyPatcher : ThoughtWorks.CruiseControl.Core.ITask
    {
        enum AssemblyType
        {
            Title,
            Description,
            Configuration,
            Company,
            Product,
            Copyright,
            Trademark,
            Culture,
            Version,
            FileVersion,
        }

        [ReflectorArray("filenames", Required = true)]
        public string[] filenames { get; set; }

        public string version;
        [ReflectorProperty("patchtype")]
        public string patchtype;
        [ReflectorProperty("patchtext")]
        public string patchtext;

        private AssemblyType vtype;
        void ThoughtWorks.CruiseControl.Core.ITask.Run(ThoughtWorks.CruiseControl.Core.IIntegrationResult result)
        {
            version = result.Label;
            if (!String.IsNullOrEmpty(patchtext))
                version = patchtext;
            foreach (string filename in filenames)
            {
                if (!System.IO.File.Exists(filename))
                {
                    throw new Exception("File doesn't exists!");
                }

                List<string> lines = new List<string>(System.IO.File.ReadAllLines(filename));
                foreach (string ass in patchtype.Split(','))
                {
                    try
                    {
                        vtype = (AssemblyType)Enum.Parse(typeof(AssemblyType), ass.Trim());
                    }
                    catch
                    {
                        throw new Exception("Invalid type!");
                    }
                    int lineIndex = -1;
                    lineIndex = lines.FindIndex(line => line.StartsWith(String.Format(("[assembly: Assembly{0}("), vtype)));
                    if (lineIndex != -1)
                    {
                        string text = String.Format("[assembly: Assembly{0}(\"{1}\")]", vtype, version);
                        lines[lineIndex] = text;
                    }
                }
                System.IO.File.WriteAllLines(filename, lines.ToArray<string>());
            }
        }
    }
}